// pages/camera/camera.js
Page({
  // 数据初始化
  data: {
      currentTab: 0,
      winWidth: 0,
      winHeight: 0,
  },

  // 获取窗口尺寸
  onLoad: function() {
      // 获取窗口尺寸
      wx.getSystemInfo({
          success: (res) => {
              this.setData({
                  winWidth: res.windowWidth,
                  winHeight: res.windowHeight
              })
          }
      })
      // 检查相机权限
      this.checkCameraPermission()
      // 创建相机上下文
      this.ctx = wx.createCameraContext()
  },

  // 检查相机权限
  checkCameraPermission() {
      // 获取设置
      wx.getSetting({
          // getSetting的成功回调函数
          success: (res) => {
              if (!res.authSetting['scope.camera']) {
                  // 相机授权
                  wx.authorize({
                      scope: 'scope.camera',
                      // authorized的成功回调函数
                      success: () => {
                          console.log('相机权限已授权')
                      },
                      // authorize的失败回调函数
                      fail: () => {
                          // 提示信息
                          wx.showModal({
                              title: '权限提示',
                              content: '需要相机权限才能使用拍摄功能',
                              confirmText: '去设置',
                              // showModal的成功回调函数
                              success: (res) => {
                                  if (res.confirm) wx.openSetting()
                              }
                          })
                      }
                  })
              }
          }
      })
  },

  // 选项卡切换
  switchNav: function(e) {
      var that = this;
      if (that.data.currentTab === e.target.dataset.current) {
          return false;
      } else {
          that.setData({ currentTab: e.target.dataset.current })
      }
  },

  // 拍照
  takePhoto() {
      this.ctx.takePhoto({
          quality: 'high',
          success: (res) => {
              this.setData({
                  src: res.tempImagePath
              })
          }
      })
  },

  // 开始录制
  startRecord() {
      this.ctx.startRecord({
          success: (res) => {
              console.log('startRecord')
          }
      })
  },

  // 结束录制
  stopRecord() {
      this.ctx.stopRecord({
          success: (res) => {
              this.setData({
                  src: res.tempThumbPath,
                  videoSrc: res.tempVideoPath
              })
          }
      })
  },
  // 错误
  error(e) {
      console.log(e.detail)
  }
})